from sqlalchemy.exc import SQLAlchemyError
from flask_jwt_extended import create_access_token, create_refresh_token, decode_token
from datetime import datetime
import sys
sys.path.append("/")
from app.models.user import User, Role, db, Department, FinancialBusiness
from app.schemas.financial import financial_schema, manager_update_business_schema



class FinancialService:

    @staticmethod
    def check_user_department(user_id):
        user = User.query.filter_by(id=user_id).first()
        department = Department.query.filter_by(name='financial_department').first()

        if department == user.department :
            return True
        else:
            return False


    @staticmethod
    def get_business_by_id(business_id):
        return FinancialBusiness.query.filter_by(id=business_id).first()

    @staticmethod
    def get_all_businesses():
        return FinancialBusiness.query.all()


    @staticmethod
    def check_manager_department(user_id):
        user = User.query.filter_by(id=user_id).first()
        manager = Role.query.filter_by(name='financial_manager').first()

        if manager in user.roles :
            return True
        else:
            return False



    @staticmethod
    def update_business(business_id, update_data):

        business = FinancialBusiness.query.filter_by(id=business_id).first()
        if not business:
            return None, "Business not found"

        manager_update_business_schema.session = db.session
        # 验证更新数据
        errors = manager_update_business_schema.validate(update_data)
        if errors:
            return None, errors

        # 更新字段
        for key, value in update_data.items():
            if hasattr(business, key):
                setattr(business, key, value)

        try:

            db.session.commit()
            return financial_schema.dump(business), None
        except SQLAlchemyError as e:
            db.session.rollback()
            return None, str(e)



    @staticmethod
    def add_business(add_data):
        # 验证并加载数据

        business = financial_schema.load(add_data)

        try:
            db.session.add(business)
            db.session.commit()
            return financial_schema.dump(business), None

        except SQLAlchemyError as e:
            db.session.rollback()
            return None, str(e)

    @staticmethod
    def delete_business(business_id):
        business = FinancialBusiness.query.filter_by(id=business_id).first()
        if not business:
            return None, "Business not found"

        try:
            db.session.delete(business)
            db.session.commit()
            return True, None
        except SQLAlchemyError as e:
            db.session.rollback()
            return False, str(e)